package cn.usian.jyzx.gateway.filter;

import cn.usian.jyzx.common.util.UserInfoThreadLocalUtil;
import cn.usian.jyzx.model.constant.Constant;
import cn.usian.jyzx.model.entity.user.UserInfo;
import cn.usian.jyzx.model.vo.common.Result;
import cn.usian.jyzx.model.vo.common.ResultCodeEnum;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @TODO:
 * @Author:baimu
 * @Date:2024 11 06 09 14
 **/
@Component
@Slf4j
public class LoginFilter implements GlobalFilter{

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        log.info("进入LoginFilter过滤器");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        log.info("当前接口访问的path:{}",path);
        if (path.contains("/auth")){
            log.info("当前接口需要登录，包含/auth");

            HttpHeaders headers = request.getHeaders();
            String token = headers.getFirst("token");
            log.info("token:{}",token);
            if (StringUtils.isEmpty(token)){
                log.info("token为空");
                //没有token。即没有登录--》return 208
                Result result = Result.build(null, ResultCodeEnum.LOGIN_AUTH_ERROR);
                String s = JSON.toJSONString(result);
                log.info("返回的json:{}",s);
                DataBuffer wrap = response.bufferFactory().wrap(s.getBytes());
                response.getHeaders().setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
                Mono<DataBuffer> just = Mono.just(wrap);
                return response.writeWith(just);
            }else {
                log.info("token不为空，用token 去查询redis 查询");
                String userInfoStr = (String)redisTemplate.opsForValue().get(Constant.LOGIN_TOKEN_KEY + token);
                log.info("userInfoStr:{}",userInfoStr);
                if(StringUtils.isEmpty(userInfoStr)){
                    log.info("redis中不存在token");
                    Result result = Result.build(null, ResultCodeEnum.LOGIN_AUTH_ERROR);
                    String s = JSON.toJSONString(result);
                    log.info("返回的json:{}",s);
                    DataBuffer wrap = response.bufferFactory().wrap(s.getBytes());
                    response.getHeaders().setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
                    Mono<DataBuffer> just = Mono.just(wrap);
                    return response.writeWith(just);
                }else {
                    ThreadLocal<String> stringThreadLocal = new ThreadLocal<>();
                    stringThreadLocal.set(userInfoStr);

                    UserInfo userInfo = JSON.parseObject(userInfoStr, UserInfo.class);
                    log.info("userInfo:{}",userInfo.toString());
                    UserInfoThreadLocalUtil.setUserInfo(userInfo);
                    log.info("往UserInfoThreadLocalUtil设置UserInfo：{}", JSON.toJSONString(userInfo));


                    return chain.filter(exchange);

                }



            }



        }else {
            return chain.filter(exchange);
        }



    }

}
